import { MessageBox, Message } from "element-ui";
import store from "@/store";
import Vue from "vue";

import {
  removeToken,
  removeTokenTime,
  removerefreshToken,
  removerefreshtokenTime,
} from "@/utils/auth";

Vue.prototype.$confirm = MessageBox.confirm;
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

// 重新登录操作
export function gotoLogin() {
  Vue.prototype
    .$confirm("您的登录信息已失效, 请重新登录!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      // store.dispatch('user/logout').then(() => {
      //   location.href = '/login'
      // })
      removeToken();
      removeTokenTime();
      removerefreshToken();
      removerefreshtokenTime();
      location.href = "/login";
    })
    .catch(() => {
      // store.dispatch('user/logout').then(() => {
      //   location.href = '/login'
      // })
      removeToken();
      removeTokenTime();
      removerefreshToken();
      removerefreshtokenTime();
      location.href = "/login";
    });
}

/*
  保留dig位数小数，并返回对应有要求的数值
  @param {number} num 要保留小数的数值
  @param {number} dig 保留几位小数
  @param {string} type 保留类型，1-浮点数 2-字符串
  @return {number} 保留小数后的数值
*/
export function keepDecimal(num, dig, type) {
  if (type === 1) {
    return parseFloat(num.toFixed(dig));
  } else if (type === 2) {
    return num.toFixed(dig);
  } else {
    return num;
  }
}

// 合并相同key的项
export function mergeObjects(arr) {
  return arr.reduce((acc, current) => {
    const existing = acc.find((item) => item.key === current.key);
    if (existing) {
      existing.val += ` ${current.val}`;
    } else {
      acc.push({ ...current });
    }
    return acc;
  }, []);
}

// 拆分相同key的项
export function splitAndMergeObjects(arr) {
  return arr
    .reduce((acc, current) => {
      const existing = acc.find((item) => item.key === current.key);
      const valArray = current.val.split(" "); // 按空格拆分 val
      if (existing) {
        // 如果已存在，合并数组
        existing.val = existing.val.concat(valArray);
      } else {
        // 如果不存在，添加新对象，val 作为数组
        acc.push({ key: current.key, val: valArray });
      }
      return acc;
    }, [])
    .map((item) => {
      // 将每个 val 数组拆分成多个对象
      return item.val.map((val) => ({ key: item.key, val: val }));
    })
    .flat(); // 使用 flat() 将数组扁平化
}

// 递归处理数据中的大数
export function handleBigNumbers(data) {
  if (typeof data === "number") {
    // 如果是数字，且超过 Number.MAX_SAFE_INTEGER，则转换为 BigInt
    if (data > Number.MAX_SAFE_INTEGER || data < Number.MIN_SAFE_INTEGER) {
      return BigInt(data);
    }
    return data;
  } else if (typeof data === "object" && data !== null) {
    // 如果是对象或数组，递归处理每个属性或元素
    const newData = Array.isArray(data) ? [] : {};
    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        newData[key] = handleBigNumbers(data[key]);
      }
    }
    return newData;
  }
  // 其他类型直接返回
  return data;
}

export function updateNumberValue(inputValue) {
  // 如果输入为空，返回0
  if (inputValue === "") {
    return 0;
  }
  // 移除多余的字符，只保留数字、正负号和小数点
  let cleanedValue = inputValue.replace(/[^0-9.-]/g, "");
  // 处理第一位为小数点的情况，在前面补零
  if (cleanedValue.startsWith(".")) {
    cleanedValue = "0" + cleanedValue;
  }
  // 处理输入中出现多个小数点的情况，只保留第一个小数点
  if (cleanedValue.indexOf(".") !== cleanedValue.lastIndexOf(".")) {
    cleanedValue = cleanedValue.replace(/\.+$/, "");
  }
  // 处理输入中出现多个负号的情况，只保留第一个负号
  if (cleanedValue.indexOf("-") !== cleanedValue.lastIndexOf("-")) {
    cleanedValue = cleanedValue.replace(/-+$/, "");
  }
  // 处理输入中出现负号不在第一位的情况，将负号移到第一位
  if (cleanedValue.indexOf("-") !== 0 && cleanedValue.indexOf("-") !== -1) {
    cleanedValue = "-" + cleanedValue.replace("-", "");
  }
  // 处理小数点后最多三位的情况
  if (cleanedValue.includes(".")) {
    const integerPart = cleanedValue.split(".")[0];
    const decimalPart = cleanedValue.split(".")[1].slice(0, 3); // 取小数点后最多三位
    cleanedValue = integerPart + "." + decimalPart;
  }
  // 将处理后的值转换为数字类型
  const numberValue = parseFloat(cleanedValue);
  // 如果转换失败或者值为空，返回0
  if (isNaN(numberValue)) {
    return 0;
  }
  return numberValue;
}

/**
 * 将秒级时间戳转换为年月日小时分钟秒的日期格式
 * @param {number} timestamp - 秒级时间戳
 * @returns {string} 格式化的日期字符串 (YYYY-MM-DD HH:mm:ss)
 */
export function timestampToDateString(timestamp) {
  if (typeof timestamp !== "number" || isNaN(timestamp)) {
    throw new Error("Invalid timestamp");
  }

  const date = new Date(timestamp * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 将年月日小时分钟秒的日期格式转换为秒级时间戳
 * @param {string} dateString - 日期字符串 (YYYY-MM-DD HH:mm:ss)
 * @returns {number} 秒级时间戳
 */
export function dateStringToTimestamp(dateString) {
  if (typeof dateString !== "string") {
    throw new Error("Invalid date string");
  }

  const [datePart, timePart] = dateString.split(" ");
  if (!datePart || !timePart) {
    throw new Error("Invalid date format");
  }

  const [year, month, day] = datePart.split("-").map(Number);
  const [hours, minutes, seconds] = timePart.split(":").map(Number);

  if (
    isNaN(year) ||
    isNaN(month) ||
    isNaN(day) ||
    isNaN(hours) ||
    isNaN(minutes) ||
    isNaN(seconds)
  ) {
    throw new Error("Invalid date values");
  }

  const date = new Date(
    Date.UTC(year, month - 1, day, hours, minutes, seconds)
  );
  return Math.floor(date.getTime() / 1000);
}
